package cn.net.yugu.doraemon.springweb.advice;

import cn.net.yugu.doraemon.api.common.response.DataResult;
import cn.net.yugu.doraemon.springweb.accesslog.AccessLog;
import cn.net.yugu.doraemon.springweb.accesslog.AccessLogHolder;
import cn.net.yugu.doraemon.springweb.annotation.ResponseNotIntercept;
import cn.net.yugu.doraemon.springweb.config.YgWebProperties;
import cn.net.yugu.doraemon.springweb.constant.YgConstant;
import cn.net.yugu.doraemon.springweb.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @description:
 * @author: wanghongli
 * @create: 2022-07-31 22:14:19
 */
@Slf4j
@RestControllerAdvice
public class YgResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Resource
    private YgWebProperties ygWebProperties;
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
        final String beginMills = MDC.get(YgConstant.HTTP_REQUEST_TIMESTAMP_FLAG);
        if (beginMills != null) {
            long costMills = System.currentTimeMillis() - Long.parseLong(beginMills);
            log.info("request=>path:{} method:{} resp:{} cost:{}", req.getServletPath(), request.getMethod(), JSONUtil.toJSONString(body), costMills);
        } else {
            log.info("request=>path:{} method:{} resp:{}", req.getServletPath(), request.getMethod(), JSONUtil.toJSONString(body));
        }
        if (ygWebProperties.isThreadLocalAccessLogEnable()) {
            AccessLog accessLog = AccessLogHolder.get();
            accessLog.setResponseBody(JSON.toJSONString(body));
        }

        if (returnType.getDeclaringClass().isAnnotationPresent(ResponseNotIntercept.class)) {
            //若在类中加了@ResponseNotIntercept 则该类中的方法不用做统一的拦截
            return body;
        }
        if (Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(ResponseNotIntercept.class)) {
            //若方法上加了@ResponseNotIntercept 则该方法不用做统一的拦截
            return body;
        }
        if (!ygWebProperties.isResponseWrapperEnable()) {
            return body;
        }
        if (body instanceof DataResult) {
            return body;
        }
        if (body instanceof  String) {
            return JSON.toJSONString(DataResult.successWithData(body));
        }
        return DataResult.successWithData(body);
    }


}
